package com.shujia.flink.sql

import org.apache.flink.streaming.api.scala.StreamExecutionEnvironment
import org.apache.flink.table.api.EnvironmentSettings
import org.apache.flink.table.api.bridge.scala.StreamTableEnvironment
import org.apache.flink.streaming.api.scala._
import org.apache.flink.table.api._
import org.apache.flink.table.api.bridge.scala._
import org.apache.flink.types.Row

object Demo3ReadkafkaFormatJson {
  def main(args: Array[String]): Unit = {
    //flink  流处理的环境
    val bsEnv: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    //设置flink  sql 配置
    val bsSettings: EnvironmentSettings = EnvironmentSettings
      .newInstance()
      .useBlinkPlanner() // 使用blink 的计划器（解析sql）
      .inStreamingMode()
      .build()

    //创建table 环境
    val bsTableEnv: StreamTableEnvironment = StreamTableEnvironment.create(bsEnv, bsSettings)

    /**
      * json: 格式的数据
      * flink 会自动将json格式和 表结构进行映射
      *
      */

    bsTableEnv.executeSql(
      """
        |
        |CREATE TABLE student_json (
        | id STRING,
        | name STRING,
        | age BIGINT,
        | gender STRING,
        | clazz STRING
        |) WITH (
        | 'connector' = 'kafka',
        | 'topic' = 'student',
        | 'properties.bootstrap.servers' = 'master:9092',
        | 'properties.group.id' = 'asdasdasd',
        | 'format' = 'json',
        | 'scan.startup.mode' = 'earliest-offset',
        | 'json.ignore-parse-errors' = 'true'
        |)
        |
        |
      """.stripMargin)


    /**
      * print； 用于测试的表
      *
      * LIKE ; 基于一个表的表结构创建一个新的表
      *
      * EXCLUDING ALL： 爬起原表所有的属性
      *
      */
    /* bsTableEnv.executeSql(
        """
          |CREATE TABLE print_table WITH ('connector' = 'print')
          |LIKE student_json (EXCLUDING ALL)
          |
        """.stripMargin)


      bsTableEnv.executeSql(
        """
          |insert into print_table
          |select * from student_json
          |
        """.stripMargin)*/


    bsTableEnv.executeSql(
      """
        |create table avg_age_print(
        |clazz STRING,
        |ageAge DOUBLE
        |)WITH(
        |'connector' = 'print'
        |)
        |
      """.stripMargin)


    bsTableEnv.executeSql(
      """
        |insert into avg_age_print
        |select clazz,avg(age) as avgAge from student_json  group by clazz
        |
      """.stripMargin)






    //转换成流进行打印
    //    bsTableEnv.from("student_json").toAppendStream[Row].print()
    //    bsEnv.execute()

  }
}
